#include "databasemanager.h"
#include <QDate>
#include <QSqlQuery>

int DatabaseManager::UID=0;
DatabaseManager::DatabaseManager(){
    db = initDatabase();
}

// 析构函数，关闭数据库连接
DatabaseManager::~DatabaseManager() {
    if (db.isOpen())
        db.close();
}

QSqlDatabase& DatabaseManager ::getDatabase() {
        static QSqlDatabase db = initDatabase();
        return db;
}

int& DatabaseManager::getUID(){
    return UID;
}

void DatabaseManager::initUID(int id){
    UID=id;
}

QSqlDatabase DatabaseManager::initDatabase() {
        QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
        db.setHostName("8.148.7.72");
        db.setDatabaseName("tomato");
        db.setUserName("user");
        db.setPassword("qydwhyd");

        if (!db.open()) {
            qCritical() << "Failed to open database:" << db.lastError().text();
        }
        else
            qCritical() << "Success to open database:" << db.lastError().text();
        return db;

}

//添加数据：测试成功
void DatabaseManager::insert_history(QString task_name,QString task_type,int duration)
{
    QSqlQuery query(DatabaseManager::getDatabase());

    QDate currentDate = QDate::currentDate();
    QString dateString = currentDate.toString("yyyy-MM-dd");

    query.prepare("INSERT INTO history (user,task_name, task_type, duration, date) VALUES (?, ?, ?, ?,?)");
    query.addBindValue(UID);
    query.addBindValue(task_name);
    query.addBindValue(task_type);
    query.addBindValue(duration);
    query.addBindValue(dateString);

    if (!query.exec()) {
        qDebug() << "Failed to insert into history: " << query.lastError().text();
    }
}
void DatabaseManager::insert_task(QString task_name,QString end_date)
{
    qDebug()<<"insert_task begin";
    QSqlQuery query(DatabaseManager::getDatabase());

    query.prepare("INSERT INTO task (user,task_name,end_date) VALUES (?, ?, ?)");
    query.addBindValue(UID);
    query.addBindValue(task_name);
    query.addBindValue(end_date);
    qDebug() << "end_date"<<end_date;
    if (!query.exec()) {
        qDebug() << "Failed to insert into history: " << query.lastError().text();
    }
}
